﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MKAdmin.DTO.Web.Common;

namespace MKAdmin.ToolKit
{
    /// <summary>
    /// sql分页方法
    /// </summary>
    public static class SqlPagingHelper
    {
        /// <summary>
        /// 通用生成sql分页方法
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sortingSql"></param>
        /// <returns></returns>
        public static string GetPagingSql(string sql, int pageIndex, int pageSize, string sortingSql)
        {
            var resultSql = string.Empty;
            int pageLowerIndex = (pageIndex - 1) * pageSize;
            int pageUpperIndex = pageIndex * pageSize;

            if (pageUpperIndex > 0)
                resultSql = $"SELECT * FROM (SELECT *, {pageIndex} AS PageIndex, {pageSize} AS PageSize, COUNT(1) OVER() AS TotalCount, ROW_NUMBER() OVER({sortingSql})AS ROW_NUM From ({sql}) TempA) TempB Where ROW_NUM > {pageLowerIndex} And ROW_NUM <= {pageUpperIndex}";
            else
                resultSql = $"SELECT *, {pageIndex} AS PageIndex, {pageSize} AS PageSize, COUNT(1) OVER() AS TotalCount FROM ({sql}) TEMP {sortingSql}";

            return resultSql;
        }

        /// <summary>
        /// 转换分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static PagingList<T> ConvertToPagingList<T>(this DataTable dataTable) where T : class, new()
        {
            var data = new PagingList<T>();
            //foreach (DataRow dr in dataTable.Rows)
            //    data.data.Add(dr.ToInfo<T>());
            data.data.AddRange(dataTable.ToList<T>());

            if (dataTable.Rows.Count > 0)
            {
                data.count = Convert.ToInt32(dataTable.Rows[0]["TotalCount"]);
                //data.pageIndex = Convert.ToInt32(dataTable.Rows[0]["PageIndex"]);
                //data.pageSize = Convert.ToInt32(dataTable.Rows[0]["PageSize"]);
            }
            return data;
        }
    }
}
